/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.victor.lib.core;

import ohos.agp.components.Attr;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.app.Context;

public class LoadingView extends Image {
    private LoadingDrawable mLoadingDrawable;

    public LoadingView(Context context) {
        super(context);
        initListeners(this);
    }

    public LoadingView(Context context, AttrSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
        initListeners(this);
    }

    private void initAttrs(Context context, AttrSet attrs) {
        try {
            String loadingRendererName = null;
            if (attrs != null) {
                Attr attr = attrs.getAttr("loading_renderer").orElse(null);
                if (attr != null) {
                    loadingRendererName = attr.getStringValue();
                }
            }
            LoadingRenderer loadingRenderer = LoadingRendererFactory.createLoadingRenderer(context, LoadingRendererFactory.parseRendererNameToId(loadingRendererName));
            setLoadingRenderer(loadingRenderer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setLoadingRenderer(LoadingRenderer loadingRenderer) {
        stopAnimation();
        mLoadingDrawable = new LoadingDrawable(this, loadingRenderer);
        addDrawTask(mLoadingDrawable, DrawTask.BETWEEN_CONTENT_AND_FOREGROUND);
    }

    private void initListeners(Component component) {
        component.setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
//                startAnimation();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                stopAnimation();
            }
        });
    }

    public void startAnimation() {
        if (mLoadingDrawable != null) {
            mLoadingDrawable.start();
        }
    }

    public void stopAnimation() {
        if (mLoadingDrawable != null) {
            mLoadingDrawable.stop();
        }
    }
}
